import tkinter as tk
from tkinter import ttk, messagebox
import os
import sys
import subprocess
import importlib.util
import importlib.machinery

# 获取资源路径
def get_resource_path(relative_path):
    """获取资源的绝对路径，适用于开发环境和PyInstaller打包后的环境"""
    try:
        # PyInstaller创建临时文件夹，将路径存储在_MEIPASS中
        base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
        return os.path.join(base_path, relative_path)
    except Exception:
        return os.path.join(os.path.dirname(os.path.abspath(__file__)), relative_path)

class TranslationToolsLauncher:
    def __init__(self, root):
        self.root = root
        self.root.title("翻译工具集")
        self.root.geometry("600x400")

        # 设置窗口图标（如果有的话）
        try:
            icon_path = get_resource_path("icon.ico")
            if os.path.exists(icon_path):
                self.root.iconbitmap(icon_path)
        except Exception:
            pass

        # 创建主框架
        self.main_frame = ttk.Frame(self.root, padding="20")
        self.main_frame.pack(fill=tk.BOTH, expand=True)

        # 创建标题标签
        title_label = ttk.Label(
            self.main_frame,
            text="翻译工具集",
            font=("Arial", 16, "bold")
        )
        title_label.pack(pady=20)

        # 创建工具按钮框架
        tools_frame = ttk.Frame(self.main_frame)
        tools_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=10)

        # 创建工具按钮
        self.create_tool_button(
            tools_frame,
            "中文字符提取器",
            "从项目文件中提取中文字符串，用于后续翻译",
            self.launch_chinese_extractor,
            0
        )

        self.create_tool_button(
            tools_frame,
            "合并到PO文件",
            "将文本内容合并到PO文件中",
            self.launch_merge_to_po,
            1
        )

        self.create_tool_button(
            tools_frame,
            "PO文件翻译工具",
            "使用API自动翻译PO文件中的内容",
            self.launch_po_translator,
            2
        )

        # 创建底部状态栏
        status_frame = ttk.Frame(self.root)
        status_frame.pack(fill=tk.X, side=tk.BOTTOM, pady=5)

        status_label = ttk.Label(
            status_frame,
            text="准备就绪",
            anchor=tk.W
        )
        status_label.pack(side=tk.LEFT, padx=10)

        # 版本信息
        version_label = ttk.Label(
            status_frame,
            text="v1.0",
            anchor=tk.E
        )
        version_label.pack(side=tk.RIGHT, padx=10)

    def create_tool_button(self, parent, title, description, command, _):
        """创建工具按钮"""
        tool_frame = ttk.Frame(parent)
        tool_frame.pack(fill=tk.X, pady=10)

        # 创建按钮
        button = ttk.Button(
            tool_frame,
            text=title,
            command=command,
            width=20
        )
        button.pack(side=tk.LEFT, padx=10)

        # 创建描述标签
        desc_label = ttk.Label(
            tool_frame,
            text=description,
            wraplength=400
        )
        desc_label.pack(side=tk.LEFT, padx=10, fill=tk.X, expand=True)

    def launch_chinese_extractor(self):
        """启动中文字符提取器"""
        try:
            # 尝试导入模块
            module_path = get_resource_path("chinese_extractor.py")
            if not os.path.exists(module_path):
                messagebox.showerror("错误", "找不到chinese_extractor.py模块")
                return

            # 使用importlib.machinery加载模块
            loader = importlib.machinery.SourceFileLoader("chinese_extractor", module_path)
            chinese_extractor = loader.load_module()

            self.root.withdraw()  # 隐藏主窗口

            # 创建新的Tk实例运行提取器
            extractor_root = tk.Tk()
            chinese_extractor.ChineseExtractorApp(extractor_root)
            extractor_root.protocol("WM_DELETE_WINDOW", lambda: self.on_tool_close(extractor_root))
            extractor_root.mainloop()
        except Exception as e:
            messagebox.showerror("错误", f"启动中文字符提取器时出错：{str(e)}")
            self.root.deiconify()  # 显示主窗口

    def launch_merge_to_po(self):
        """启动合并到PO文件工具"""
        try:
            # 尝试导入模块
            module_path = get_resource_path("merge_to_po.py")
            if not os.path.exists(module_path):
                messagebox.showerror("错误", "找不到merge_to_po.py模块")
                return

            # 使用importlib.machinery加载模块
            loader = importlib.machinery.SourceFileLoader("merge_to_po", module_path)
            merge_to_po = loader.load_module()

            self.root.withdraw()  # 隐藏主窗口

            # 创建新的Tk实例运行工具
            merge_root = tk.Tk()
            merge_to_po.RecipeDisplayApp(merge_root)
            merge_root.protocol("WM_DELETE_WINDOW", lambda: self.on_tool_close(merge_root))
            merge_root.mainloop()
        except Exception as e:
            messagebox.showerror("错误", f"启动合并到PO文件工具时出错：{str(e)}")
            self.root.deiconify()  # 显示主窗口

    def launch_po_translator(self):
        """启动PO文件翻译工具"""
        try:
            # 尝试导入模块
            module_path = get_resource_path("po_translator.py")
            if not os.path.exists(module_path):
                messagebox.showerror("错误", "找不到po_translator.py模块")
                return

            # 使用importlib.machinery加载模块
            loader = importlib.machinery.SourceFileLoader("po_translator", module_path)
            po_translator = loader.load_module()

            self.root.withdraw()  # 隐藏主窗口

            # 创建翻译工具实例并运行
            translator = po_translator.POTranslator()
            translator.window.protocol("WM_DELETE_WINDOW", lambda: self.on_translator_close(translator))
            translator.run()
        except Exception as e:
            messagebox.showerror("错误", f"启动PO文件翻译工具时出错：{str(e)}")
            self.root.deiconify()  # 显示主窗口

    def on_tool_close(self, tool_window):
        """工具窗口关闭时的回调"""
        tool_window.destroy()
        self.root.deiconify()  # 显示主窗口

    def on_translator_close(self, translator):
        """翻译工具关闭时的回调"""
        translator.window.destroy()
        self.root.deiconify()  # 显示主窗口

def main():
    root = tk.Tk()
    TranslationToolsLauncher(root)
    root.mainloop()

if __name__ == "__main__":
    main()
